const Router = require('koa-router');
const router = new Router({
    prefix: '/v1/'
});

const {
    User
} = require('../../models/User.js');

const {
    isToken,
    NotEmptyValidator
} = require('../../validators/validators.js');

const {
    generateToken
} = require('../../core/utils.js');

const {
    WXManager
} = require('../../services/wx.js');
const { Auth } = require('../../middlewares/auth.js');
router.post('token', async (ctx) => {
    const result = await new isToken().validate(ctx);
  // console.log('token', result);
  let token;
  let account = result.get('body.account');
    switch (result.get('body.type')) {
        case 1:
            token = await WXManager.code2Token(account);
            break;
        case '2':
            ctx.body = 2;
            break;
        case '3':
            token = await isAccountPassword(result.get('body.userAccount'), result.get('body.userAccount'));
            break;
    }

    async function isAccountPassword(acc, pass) {
        const user = await User.isAccountPassword(acc, pass);
        return generateToken(user.id || 1, 2);
    }

    ctx.body = {
        token
    }
    // ctx.body = 'token';
});

router.post('/verify', async (ctx, next) => {
    const v = new NotEmptyValidator().validate(ctx);
    const result = Auth.verifyToken(v.get('body.token'));
    ctx.body = {
       is_valid: result
    }
})

module.exports = router;